<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拖拽效果</title>
    <style>
        *{margin: 0;padding:0;box-sizing: border-box}
        html,body,.container{
            width: 100%;
            height: 100%;
            overflow: hidden;
            position:relative;
        }
        .move{
            width: 150px;
            height: 200px;
            background: #aef;
            position: absolute;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="move"></div>
    </div>

    <script>
        let move = document.querySelector(".move");
        let container = document.querySelector(".container");

        //绑定事件
        move.addEventListener('touchstart', function(e){
            //移除过渡
            this.style.transition = 'none';
            //获取 move 元素距离左侧的偏移量
            this.l = move.offsetLeft;
            //获取按下时, 触点距离左侧的偏移量
            this.x = e.changedTouches[0].pageX;

            this.t = move.offsetTop;
            this.y = e.changedTouches[0].pageY;

        })
        
        //touchmove 事件
        move.addEventListener('touchmove', function(e){
            //获取手指滑动后, 触点距离左侧的偏移量
            let _x = e.changedTouches[0].pageX;
            //计算最终的 left 的值
            let newLeft = _x - (this.x - this.l);
            //判断边界
            if(newLeft <= 0) newLeft = 0;
            //计算最大的 left 的值
            this.maxLeft = container.offsetWidth - move.offsetWidth;
            //判断
            if(newLeft >= this.maxLeft) newLeft = this.maxLeft;

            //获取 顶部的偏移量
            let _y = e.changedTouches[0].pageY;
            let newTop = _y - (this.y - this.t);
            //设置 move 元素的 left 样式
            move.style.left = newLeft + 'px';
            move.style.top = newTop + 'px';
        });

        //touchend 事件
        move.addEventListener('touchend', function(e){
            this.style.transition = 'all 0.4s';
            //获取当前 move 元素 距离左侧的偏移
            let left = this.offsetLeft;
            //计算move居中时的 left 
            let middle = (container.offsetWidth - move.offsetWidth) / 2
            //判断
            if(left < middle){
                this.style.left = "0px";
            }else{
                this.style.left = this.maxLeft + 'px';
            }
        })
    </script>
</body>
</html>